﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace P2P_Backup.archive
{
    public enum TransferStatus { New, InProgress, Complete,Failed }
    public class FileArgs : EventArgs
    {
        public FileArgs(File file)
        {
            this.file = file;
        }
        private File file;
        public File File
        {
            get { return file; }
        }
    }

    public class File
    {
        public long Size;
        public String Path;
        public Guid Id;
        public RemotePeer BackupPeer;
        public TransferStatus Status;

        public String Name()
        {
            if (!Path.Contains('\\')) return Path;
            return Path.Substring(Path.LastIndexOf('\\') + 1);
        }
        public String FriendlySize()
        {
            string[] sizes = { "B", "KB", "MB", "GB" };
            int order = 0;
            long len = Size;
            while (len >= 1024 && order + 1 < sizes.Length)
            {
                order++;
                len = len / 1024;
            }
            return String.Format("{0:0.##} {1}", len, sizes[order]);
        }

        public virtual Stream GetWritableStream()
        {
            Console.WriteLine("Saving {0} to Disk", this.Name());
            FileStream fs = new FileStream(this.Path, FileMode.Create);
            return new CryptoStream(fs, 
                                    tools.Crypto.getAlgorithm(P2PBackup.Instance.ArchiveKey).CreateDecryptor(), 
                                    CryptoStreamMode.Write);
        }
        public virtual Stream GetReadableStream()
        {
            if (System.IO.File.Exists(this.Path))
            {
                FileStream fs = new FileStream(this.Path, FileMode.Open);
                return new CryptoStream(fs,
                                            tools.Crypto.getAlgorithm(P2PBackup.Instance.ArchiveKey).CreateEncryptor(),
                                            CryptoStreamMode.Read);                                  
            }
            Console.WriteLine("GetStream: Could not find file");
            return null;
        }

        public File(string path)
        {
            //local file
            this.Path = path;
            this.Size = new System.IO.FileInfo(path).Length;
            this.Id = Guid.NewGuid();
            this.Status = TransferStatus.New;
        }
        

        public File()
        {
            //local file from xml file
        }
    }
}
